package com.lik888.handler;

import com.lik888.Exception.myselfException;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.IOException;
import java.io.PrintWriter;

@Component
@RestControllerAdvice
public class GlobalExceptionHandler {

    @Autowired
    private AuthenticationEntryPoint authenticationEntryPoint;

    @ExceptionHandler(myselfException.class)
    public void handleAuthenticationException(myselfException e, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException, ServletException, IOException {
        // 触发AuthenticationEntryPoint的逻辑
        response.setContentType("application/json;charset=utf-8");


        PrintWriter writer = response.getWriter();
        writer.write("{" +
                "\"code\":401," +
                "\"msg\":\"未登录，访问受限，请先登录\"," +
                "\"success\":false" +
                "}");
        writer.flush();
        writer.close();
//
//        authenticationEntryPoint.commence(request, response, e);
    }
}